﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace SG.IPC.VirtualDiskService
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            var flags = args.ConvertToFlags();

            if (Environment.UserInteractive)
            {
                var isInstall = flags.HasFlag("INSTALL");
                var isUninstall = flags.HasFlag("UNINSTALL");
#if DEBUG
                var isDebug = flags.HasFlag("DEBUG");
                if (isDebug)
                {
                    if (!Debugger.IsAttached)
                        Debugger.Launch();
                    else
                        Debugger.Break();
                }
#endif

                if (isInstall && isUninstall)
                    throw new ArgumentException("Cannot do both install and uninstall!", "args");


                if (isInstall || isUninstall)
                {
                    using (var installer = new ProjectInstaller())
                    {
                        var state = new Hashtable();

                        if (isInstall)
                            installer.Install(state);
                        else
                            installer.Uninstall(state);
                    }
                }
            }
            else
            {

                ServiceBase.Run(new ServiceBase[]
                    {
                        new VirtualDiskService()
                    });
            }
        }

        private static bool HasFlag(this ISet<string> flags, string flag)
        {
            return flags.Contains(flag) || flags.Contains(flag.Substring(0, 1));
        }

        private static ISet<string> ConvertToFlags(this IEnumerable<string> args)
        {
            var flags = new HashSet<string>();
            if (args != null)
            {
                foreach (var arg in args.Where(arg => arg.StartsWith("/") && !arg.EndsWith(":")))
                {
                    flags.Add(arg.ToUpperInvariant().Substring(1));
                }
            }
            return flags;
        }
    }
}
